package com.lt.test.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.lt.test.api.KtCountService;
import com.lt.test.common.exception.CustomException;
import com.lt.test.common.util.StringUtils;
import com.lt.test.provider.dao.KtCountDao;
import com.lt.test.provider.dao.KtOtherDao;
import com.lt.test.provider.dao.KtShopTobaccoRequirementDao;
import com.lt.test.provider.dao.KtTobaccoOrderDao;
import com.lt.test.entity.QueryModel.PageFilter;
import com.lt.test.entity.QueryModel.PageQueryModel;
import com.lt.test.provider.mapper.KtCountMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 统计订单数据相关Servicer
 * 创建人：lt
 * 创建时间：15:10 2018/1/25
 */
@Service(version = "1.0.0")
public class KtCountServiceImpl implements KtCountService {
	private static Logger log = LoggerFactory.getLogger(KtCountServiceImpl.class);
    @Autowired
    KtCountMapper ktCountMapper;
    @Autowired
    KtOtherDao ktOtherDao;
    @Autowired
    KtTobaccoOrderDao ktTobaccoOrderDao;

    @Autowired
    KtShopTobaccoRequirementDao ktShopTobaccoRequirementDao;
    
    @Autowired
    KtCountDao ktCountDao;
    
    @Override
    public List<Map<String, Object>> getKtCollect(Map<String, String> parameter) {
        List<Map<String, Object>> list = ktCountMapper.selectKtCollect(parameter);
        return list;
    }

    @Override
    public List<Map<String, Object>> getKtInsCargo(Map<String, String> parameter) {
        return ktCountMapper.selectKtInsCargo(parameter);
    }

    @Override
    public List<Map<String, Object>> getKtOutCargo(Map<String, String> parameter) {
        return ktCountMapper.selectKtOutCargo(parameter);
    }

    @Override
    public List<Map<String, Object>> findShipmentOrderByLsatCreateTime(Map<String, String> params) throws CustomException {
        List<Map<String, Object>> result;

        //初次获取
        if (params.get("lastOrderTime") == null || "".equals(params.get("lastOrderTime"))) {
            try {
                result = ktCountMapper.findTenShipmentOrder(params);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("获取初始化十条出库订单失败");
            }
        } else {
            try {
                result = ktCountMapper.findShipmentOrderByLastOrderTime(params);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("根据最后更新时间获取出库订单失败");
            }
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> getKtShipmentOrderByTime(Map<String, String> stringMap) throws CustomException {
        stringMap = getBeginTime(stringMap);

        Integer pageSize = Integer.valueOf(stringMap.get("pageSize"));

        Long page = stringMap.get("page") == null ? 1 : Long.valueOf(stringMap.get("page"));

        Long beginNum = ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());

        try {
            return ktCountMapper.getKtShipmentOrderByBeginTimeAndEndTime(stringMap);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("根据时间查询扫码出库记录失败");
        }
    }

    @Override
    public List<Map<String, Object>> gatKtClassifiedTobaccoSales(Map<String, String> parameter) {
        List<Map<String, Object>> list = new ArrayList<>();
        String[] cstPrice = {"1.00~199.00","200.00~399.00","400.00~599.00","600.00~1200.00"};
        for(int i = 0; i < cstPrice.length; i++){
            String cstPrice1 = cstPrice[i].split("~")[0];
            String cstPrice2 = cstPrice[i].split("~")[1];
            parameter.put("cstPrice1",cstPrice1);
            parameter.put("cstPrice2",cstPrice2);
            List listMap = ktCountMapper.selectKtClassifiedTobaccoSales(parameter);
            if (listMap.size() > 0) {
                list.add((Map<String, Object>) listMap.get(0));
            }
        }
        return list;
    }

    
    private Map<String, String> getBeginTime(Map<String, String> stringMap) {
        if (stringMap.get("beginTime") == null || stringMap.get("beginTime").equals("")) {
            Calendar ca = Calendar.getInstance();
            ca.setTime(new Date());
            ca.add(Calendar.MONTH, -1);
            Date firstDay = ca.getTime();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd ");
            stringMap.put("beginTime", sf.format(firstDay));
        }
        return stringMap;
    }

	@Override
	public JSONObject getktInstore(Long page,Long pageSize,String filters,String sortName,String sortOrder) {

		Long beginNum = page + 1;
	    Long endNum = beginNum + pageSize ;
	    PageQueryModel pageQueryModel = new PageQueryModel();
	    pageQueryModel.setBeginNum(beginNum);
		pageQueryModel.setEndNum(endNum);
		pageQueryModel.setFilters(getInStorePageQueryModel(filters));
		pageQueryModel.setSortName(sortName);
		pageQueryModel.setSortOrder(sortOrder);
		
		List<PageFilter> filts = getInStorePageQueryModel(filters);
		Map<Object, Object> paramMap = new HashMap<>();
		PageFilter pageFilter = filts.get(0);
		String filterValue2 = pageFilter.getFilterValue();
		PageFilter pageFilter2 = filts.get(1);
		String filterValue3 = pageFilter2.getFilterValue();
		paramMap.put("typId", filterValue2);
		paramMap.put("shopId", filterValue3);
		paramMap.put("beginNum", beginNum);
		paramMap.put("endNum", endNum);
		paramMap.put("sortName", sortName);
		paramMap.put("sortOrder", sortOrder);
		
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			inStoreDOList = ktCountMapper.findInStoreByPage(pageQueryModel);
			recordCount = ktCountMapper.findInStoreCount(pageQueryModel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}
	
	private static String object2Str(JSONObject o,String k){
		if(o.containsKey(k)){
			return String.valueOf(o.get(k));
		}
		return "";
	}
	private static List<PageFilter> getInStorePageQueryModel(String filters){
		List<PageFilter> filterList = new ArrayList<PageFilter>();
		if(filters != null && !filters.trim().equals("")){
			JSONArray arr = JSONArray.fromObject(filters);
			for (int i = 0; i < arr.size(); i++) {
				JSONObject obj = (JSONObject)arr.get(i);
				filterList.add(new PageFilter(object2Str(obj,"fn"),object2Str(obj,"ft"),object2Str(obj,"fv")));
			}
		}
		return filterList;
	}

	@Override
	public List<Map<String, Object>> selectKtInstoreForExcel(Map<String, String> parameter) {
		return ktCountMapper.selectKtInstoreForExcel(parameter);
	}

	@Override
	public List<Map<String, String>> findProductType(String levelDeep) {
		return ktCountMapper.findProductType(levelDeep);
	}

	@Override
	public List<Map<String, String>> findShopName() {
		return ktCountMapper.findShopName();
	}

	@Override
	public List<Map<String, Object>> getShopNameToSelect(Map<String, String> params) throws CustomException {

		return ktCountMapper.getShopNameToSelect(params);
	}

	@Override
	public JSONObject getKtPss(Map<String, String> stringMap,int searchType) {
		Long pageSize = Long.valueOf(stringMap.get("limit"));

        Long page = Long.valueOf(stringMap.get("offset"));

        Long beginNum = page + 1;
        Long endNum = beginNum + pageSize;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			String shopName = stringMap.get("shopName");
			if(shopName.length() <3){
				inStoreDOList = new ArrayList<Map<String,Object>>();
				result.put("rows", inStoreDOList);
				result.put("total", 0);
				return JSONObject.fromObject(result);
			}
			if(searchType == 0){
				inStoreDOList = ktCountMapper.selectKtPss(stringMap);
				recordCount = ktCountMapper.selectKtPssCount(stringMap);
			}else if (searchType == 1) {
				inStoreDOList = ktCountMapper.selectKtPssGBForeType(stringMap);
				recordCount = ktCountMapper.selectKtPssGBForeTypeCount(stringMap);
			}else if (searchType == 3) {
				inStoreDOList = ktCountMapper.selectKtPssGBType(stringMap);
				recordCount = ktCountMapper.selectKtPssGBTypeCount(stringMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}

	@Override
	public JSONObject getKtProdInfo(Long page,Long pageSize,String filters,String sortName,String sortOrder) {


        Long beginNum = page +1;
        Long endNum = beginNum + pageSize ;
        PageQueryModel pageQueryModel = new PageQueryModel();
		pageQueryModel.setBeginNum(beginNum);
		pageQueryModel.setEndNum(endNum);
		pageQueryModel.setFilters(getInStorePageQueryModel(filters));
		pageQueryModel.setSortName(sortName);
		pageQueryModel.setSortOrder(sortOrder);
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			inStoreDOList = ktCountMapper.selectKtProdInfo(pageQueryModel);
			recordCount = ktCountMapper.selectKtProdInfoCount(pageQueryModel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}

	@Override
	public List<Map<String, String>> findSupplierName(String typeId) {
		return ktCountMapper.findSupplierName(typeId);
	}

	@Override
	public JSONObject getKtInOutInfo(Long page, Long pageSize, String filters,String sortName,String sortOrder) {
		
        Long beginNum = page + 1;
        Long endNum = beginNum + pageSize ;
        PageQueryModel pageQueryModel = new PageQueryModel();
		pageQueryModel.setBeginNum(beginNum);
		pageQueryModel.setEndNum(endNum);
		pageQueryModel.setFilters(getInStorePageQueryModel(filters));
		pageQueryModel.setSortName(sortName);
		pageQueryModel.setSortOrder(sortOrder);
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			inStoreDOList = ktCountMapper.selectKtInOutInfo(pageQueryModel);
			recordCount = ktCountMapper.selectKtInOutInfoCount(pageQueryModel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}

	@Override
	public JSONObject getKtCollectMoney(Map<String, String> stringMap,int searchType) {
		Long pageSize = Long.valueOf(stringMap.get("limit"));
        Long page = Long.valueOf(stringMap.get("offset"));

        Long beginNum = page;
        Long endNum = beginNum + pageSize;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			if(searchType == 0){
				inStoreDOList = ktCountMapper.selectKtCollectMoney(stringMap);
				recordCount = ktCountMapper.selectKtCollectMoneyCount(stringMap);
			}else if(searchType == 1){
				inStoreDOList = ktCountMapper.selectKtCollectMoneyGBShop(stringMap);
				recordCount = ktCountMapper.selectKtCollectMoneyGBShopCount(stringMap);
			}else if(searchType == 2){
				inStoreDOList = ktCountMapper.selectKtCollectMoneyGBOperator(stringMap);
				recordCount = ktCountMapper.selectKtCollectMoneyGBOperatorCount(stringMap);
			}else if(searchType == 3){
				inStoreDOList = ktCountMapper.selectKtCollectMoneyGBDate(stringMap);
				recordCount = ktCountMapper.selectKtCollectMoneyGBDateCount(stringMap);
			}else if(searchType == 4){
				final String[] searchTypeCols = new String[]{"现金","POS刷卡","商城微支付","农行微信主扫","农行微信被扫","银联在线","POS优惠","商户微信","商户支付宝","其他"};
				inStoreDOList = ktCountMapper.selectKtCollectMoneyGBType(stringMap);
				recordCount = ktCountMapper.selectKtCollectMoneyGBTypeCount(stringMap);
				for (int i = 0; i < searchTypeCols.length; i++) {
					boolean isexist = false;
					for(Map<String, Object> oHashMap : inStoreDOList){
						if(oHashMap.get("TYPE_NAME").equals(searchTypeCols[i])){
							isexist = true;
							break;
						}
					}
					if(!isexist){
						Map map = new HashMap<String, Object>();
						recordCount += 1;
						map.put("ROWNUM_", recordCount);
						map.put("TYPE_NAME",searchTypeCols[i]);
						map.put("TOTAL_TYPE", 0);
						map.put("BENEFIT_AMT", 0);
						map.put("TOTAL_SUM", 0);
						map.put("COUNT_TYPE", 0);
						map.put("TOTAL_PERCENT", 0);
						map.put("COUNT_PERCENT", 0);
						inStoreDOList.add(map);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}
	
	//资金对账表
	@Override
	public JSONObject ktMoneyPaysave(Long offset, Long limit, String filters,int searchType,String sortName,String sortOrder) {
		Long beginNum = offset +1;
	    Long endNum = beginNum + limit ;
	    PageQueryModel pageQueryModel = new PageQueryModel();
	    pageQueryModel.setBeginNum(beginNum);
		pageQueryModel.setEndNum(endNum);
		pageQueryModel.setFilters(getInStorePageQueryModel(filters));
		pageQueryModel.setSortName(sortName);
		pageQueryModel.setSortOrder(sortOrder);
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			if(searchType == 3){
				inStoreDOList = ktCountMapper.ktMoneyPaysave(pageQueryModel);
				//recordCount = ktCountMapper.selectKtCollectMoneyCount(pageQueryModel);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}

	@Override
	public List<Map<String, String>> findArea(Map<String, String> parameter) {
		// TODO Auto-generated method stub
		return ktCountMapper.findArea(parameter);
	}

	@Override
	public List<Map<String, Object>> getKtTobaccoOrder(Map parameter) {
		// TODO Auto-generated method stub
		//查询7天内有没有保存记录
		String shopId = parameter.get("shopId").toString();
		String year = parameter.get("year") == null ? null : parameter.get("year").toString();
		String weekNo = parameter.get("weekNo") == null ? null : parameter.get("weekNo").toString();
		String type = parameter.get("type") == null ? "1" : parameter.get("type").toString();
		List<Map<String,Object>> itemList = null;
		if("1".equals(type)){
			//先查询是否已保存数据
			itemList = ktTobaccoOrderDao.getShopTobaccoOrder(shopId,year,weekNo,type);
			if(itemList.size()==0){
				//如果没有数据
				itemList = ktTobaccoOrderDao.getKtTobaccoOrder(shopId, year, weekNo);
			}
			
		}else if("2".equals(type)){
			itemList = ktTobaccoOrderDao.getShopTobaccoOrder(shopId, year, weekNo, type);
		}
		
		return itemList;
	}

	@Override
	public void saveKtTobaccoOrder(Map parameter) {
		// TODO Auto-generated method stub
		String year = parameter.get("year") == null ? null : parameter.get("year").toString();
		String weekNo = parameter.get("weekNo") == null ? null : parameter.get("weekNo").toString();
		String type = parameter.get("type") == null ? "1": parameter.get("type").toString();
		String userId = parameter.get("operator") == null ? null : parameter.get("operator").toString();
		String shopId = parameter.get("shopId").toString();
		
		Map record = ktTobaccoOrderDao.getLastestWeekRecord(shopId, year, weekNo,type);
		String itemList = parameter.get("itemList").toString();
		JSONArray dataArray = JSONArray.fromObject(itemList);
		List<Map> orderItemList = new ArrayList<Map>();
		if(record != null) {
			ktTobaccoOrderDao.batchDelete(shopId,year,weekNo);
		}
		String batchNo = StringUtils.getUUID();
		for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
			JSONObject obj = dataArray.getJSONObject(i);
			Map orderItem = (Map) obj.toBean(obj, Map.class);
			orderItem.put("id", StringUtils.getUUID());
			orderItem.put("type", type);
			orderItem.put("batchNo", batchNo);
			orderItem.put("status", "1");
			orderItem.put("createTime", new Date());
			orderItemList.add(orderItem);
		}
		ktTobaccoOrderDao.batch(orderItemList);
	}
	
	@Override
	public void saveSingleKtTobaccoOrder(Map parameter) {
		// TODO Auto-generated method stub
		String year = parameter.get("year") == null ? null : parameter.get("year").toString();
		String weekNo = parameter.get("weekNo") == null ? null : parameter.get("weekNo").toString();
		String type = parameter.get("type") == null ? "1": parameter.get("type").toString();
		String userId = parameter.get("operator") == null ? null : parameter.get("operator").toString();
		String productCode = parameter.get("productCode").toString();
		String shopId = parameter.get("shopId").toString();
		Map record = ktTobaccoOrderDao.getRecord(shopId, year, weekNo, type, productCode);
		if(record != null){
			parameter.put("id", record.get("id").toString());
			ktTobaccoOrderDao.update(parameter);
		}else{
			parameter.put("id", StringUtils.getUUID());
			parameter.put("status", "1");
			parameter.put("createTime", new Date());
			ktTobaccoOrderDao.create(parameter);
		}
	}

	@Override
	public Map<String, Object> getXYShopTobacco(Map parameter) {
		// TODO Auto-generated method stub
		String year = parameter.get("year").toString();
		String weekNo = parameter.get("weekNo").toString();
		String zoneCode = parameter.get("zoneCode") == null ? "" : parameter.get("zoneCode").toString();
		Map result = new HashMap();
		List<Map<String,Object>> shopList = ktTobaccoOrderDao.getShopList(zoneCode);
		result.put("shopList", shopList);
		
		List<Map<String,Object>> productList = ktTobaccoOrderDao.getTobaccoList(year, weekNo);
		result.put("productList", productList);
		
		List<Map<String,Object>> shopProductList = ktTobaccoOrderDao.getShopTobaccoConfirmQuantity(year, weekNo);
		result.put("shopProductList", shopProductList);
		
		return result;
	}

	@Override
	public void saveShopTobaccoRequirement(Map parameter) {
		// TODO Auto-generated method stub
		String year = parameter.get("year").toString();
		String weekNo = parameter.get("weekNo").toString();
		String productCode = parameter.get("productCode").toString();
		//查找是否有数据
		Map record = ktShopTobaccoRequirementDao.getRecord(year, weekNo, productCode);
		if(record != null){
			record.put("state", "0");
			ktShopTobaccoRequirementDao.update(record);
		}
		parameter.put("id", StringUtils.getUUID());
		parameter.put("state","1");
		parameter.put("createTime", new Date());
		ktShopTobaccoRequirementDao.create(parameter);
	}


	public List<Map<String, Object>> tablesToExcel(Map parameter){
		String year = parameter.get("year").toString();
		String weekNo = parameter.get("weekNo").toString();

		String shopIds = parameter.get("shopIds") == null ? "" : parameter.get("shopIds").toString();
		String shopNames = parameter.get("shopNames") == null ? "" : parameter.get("shopNames").toString();
		String shopIdNames = parameter.get("shopIdNames") == null ? "" : parameter.get("shopIdNames").toString();

		List<Map<String, Object>> list = ktShopTobaccoRequirementDao.tablesToExcel(year, weekNo, shopIds, shopIdNames);
		return list;
	}
	
	@Override
	public Map<String, Object> getShopStockOrSales(Map parameter) {
		// TODO Auto-generated method stub
		String type = parameter.get("type").toString();
		String zoneCode = parameter.get("zoneCode") == null ? "" : parameter.get("zoneCode").toString();
		Map result = new HashMap();
		List<Map<String,Object>> shopList = ktTobaccoOrderDao.getShopList(zoneCode);
		result.put("shopList", shopList);
		
		List<Map<String,Object>> productList = ktOtherDao.getKtProductList();
		result.put("productList", productList);
		
		if(type.equals("1")){
			//取库存数据
			List<Map<String,Object>> shopProductList = ktOtherDao.getKtShopProductStock();
			result.put("shopProductList", shopProductList);
		}else if(type.equals("2")){
			//取销售数据
			String beginTime = parameter.get("beginTime").toString();
			String endTime = parameter.get("endTime").toString();
			List<Map<String,Object>> shopProductList = ktOtherDao.getKtShopProductSales(beginTime, endTime);
			result.put("shopProductList", shopProductList);
		}
		return result;
	}

	private static Map<String, Object> Arrays2Map(String[] ColsName){
		Map<String, Object> rMap = new HashMap<String, Object>();
		for (int i = 0; i < ColsName.length; i++) {
			if (i == 0) {
				rMap.put(ColsName[i], "合计");
				continue;
			}
			rMap.put(ColsName[i], "");
		}
		return rMap;
	}
	@Override
	public Map<String, Object> getStatisPss(String[] ColsName,Map<String, String> params) {
		Map<String, Object> ColsNameMap = Arrays2Map(ColsName);
		Map<String, Object> statisticsRow =  ktCountDao.getStatisPss(Arrays.asList(ColsName), params);
		ColsNameMap.putAll(statisticsRow);
		return ColsNameMap;
	}

	@Override
	public Map<String, Object> getStatisInstore(String[] ColsName, String filters) {
		Map<String, Object> ColsNameMap = Arrays2Map(ColsName);
		Map<String, Object> statisticsRow =  ktCountDao.getStatisInstore(Arrays.asList(ColsName), getInStorePageQueryModel(filters));
		ColsNameMap.putAll(statisticsRow);
		return ColsNameMap;
	}

	@Override
	public Map<String, Object> getStatisProdInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, Object> getStatisInOut(String[] ColsName,String filters) {
		Map<String, Object> ColsNameMap = Arrays2Map(ColsName);
		Map<String, Object> statisticsRow =  ktCountDao.getStatisInOut(Arrays.asList(ColsName), getInStorePageQueryModel(filters));
		ColsNameMap.putAll(statisticsRow);
		return ColsNameMap;
	}

	@Override
	public Map<String, Object> getStatisCollectMoney(String[] ColsName,Map<String,String> stringMap,int searchType) {
		Map<String, Object> ColsNameMap = Arrays2Map(ColsName);
		Map<String, Object> statisticsRow =  new HashMap<>();
		if(searchType == 0 ||searchType == 1 ||searchType == 2 ||searchType == 3){
			statisticsRow =  ktCountDao.getStatisCollectMoneyOne(Arrays.asList(ColsName), stringMap);
		}else{
			statisticsRow =  ktCountDao.getStatisCollectMoneyTwo(Arrays.asList(ColsName), stringMap);
		}
		ColsNameMap.putAll(statisticsRow);
		return ColsNameMap;
	}

	@Override
	public List<Map<String, Object>> getTOrderItemShopAllDay(Map<String, String> params,int searchType) {
		List<Map<String, Object>> recordList = null; 
		if (searchType==0) {
			recordList = ktCountDao.getTOrderItem(params);
		}else if (searchType==1) {
			recordList = ktCountDao.getShopAllDay(params);
		}else{
			recordList = ktCountDao.getShopInstockItem(params);
		}
		return recordList;
	}
	
	
	/**
	 * 销售汇总列表
	 */
	@Override
	public JSONObject salesSummaryList(Map<String, String> parameter) {
		List<Map<String, Object>> inStoreDOList = null;
		String sumType = parameter.get("sumType");
		if(sumType.equals("10")){
				inStoreDOList = ktCountMapper.salesSummaryList(parameter);
			for(int i=0;i<inStoreDOList.size();i++){
				Map<String, Object> map = inStoreDOList.get(i);
				String state = map.get("STATE").toString();
				Object sales = map.get("SALES");
				Object sales_amount = map.get("SALES_AMONT");
				if(state.equals("-1")){
					map.put("RETURN_NUM", sales);
					map.put("RETURN_AMOUNT", sales_amount);
				}else{
					double benefit_price = Double.parseDouble(map.get("BENEFIT_PRICE").toString());
					double salesAmount = Double.parseDouble(sales_amount.toString());
					double real_amount = (salesAmount-benefit_price);
					map.put("REAL_AMOUNT", real_amount);
				}
			}
		}else if(sumType.equals("11")){
				inStoreDOList = ktCountMapper.SalesSummaryTypeAllSQL(parameter);
		}
		
		Map<String, Object> result = new HashMap<>();
		result.put("rows", inStoreDOList);
		return JSONObject.fromObject(result);
	}

	/**
	 * 获取区域
	 */
	@Override
	public JSONObject getArea(Map parameter) {
		List<Map<String, Object>> inStoreDOList = null;
		Map<String, Object> result = new HashMap<>();
		inStoreDOList = ktCountMapper.getArea(parameter);
		result.put("rows", inStoreDOList);
		return JSONObject.fromObject(result);
	}

	/**
	 * 获取店铺
	 */
	@Override
	public JSONObject getShop(Map parameter) {
		
		List<Map<String, Object>> shopList = null;
		Map<String, Object> result = new HashMap<>();
		String roleNo = parameter.get("roleNo").toString();
		
		if(roleNo.equals("1") || roleNo.equals("29")){
			parameter.put("userId", "");
			shopList = ktCountMapper.getShop(parameter);
			for(int i=0;i<shopList.size();i++){
				String nm = shopList.get(i).get("SHOP_NAME").toString();
				if(nm.length()>=13){
					String res = nm.substring(0, 12);
					String res2 = nm.substring(12);
					if(res.equals("贵州科泰易购商贸有限公司")){
						shopList.get(i).put("SHOP_NAME", res2);
					}
				}
			}
			result.put("shops", shopList);
		}else{
			if(roleNo.equals("27")){
				parameter.put("userId", "");
				shopList = ktCountMapper.getShop(parameter);
				for(int i=0;i<shopList.size();i++){
					String nm = shopList.get(i).get("SHOP_NAME").toString();
					if(nm.length()>=13){
						String res = nm.substring(0, 12);
						String res2 = nm.substring(12);
						if(res.equals("贵州科泰易购商贸有限公司")){
							shopList.get(i).put("SHOP_NAME", res2);
						}
					}
				}
				result.put("shops", shopList);
			}else{
				shopList = ktCountMapper.getShop(parameter);
				result.put("shops", shopList);
			}
		}
		
//		if(roleNo.equals("4") || roleNo.equals("26")){
//			shopList = ktCountMapper.getShop(parameter);
//			for(int i=0;i<shopList.size();i++){
//				String nm = shopList.get(i).get("SHOP_NAME").toString();
//				if(nm.length()>=13){
//					String res = nm.substring(0, 12);
//					String res2 = nm.substring(12);
//					if(res.equals("贵州科泰易购商贸有限公司")){
//						shopList.get(i).put("SHOP_NAME", res2);
//					}
//				}
//			}
//			result.put("shops", shopList);
//		}else{
//			parameter.put("userId", "");
//			shopList = ktCountMapper.getShop(parameter);
//			for(int i=0;i<shopList.size();i++){
//				String nm = shopList.get(i).get("SHOP_NAME").toString();
//				if(nm.length()>=13){
//					String res = nm.substring(0, 12);
//					String res2 = nm.substring(12);
//					if(res.equals("贵州科泰易购商贸有限公司")){
//						shopList.get(i).put("SHOP_NAME", res2);
//					}
//				}
//			}
//			result.put("shops", shopList);
//		}
		return JSONObject.fromObject(result);
	}

	/**
	 * 获取商品类型
	 */
	@Override
	public JSONObject getGoodsType() {
		
		List<Map<String, Object>> goodsTypeList = null;
		Map<String, Object> result = new HashMap<>();
		goodsTypeList = ktCountMapper.getGoodsType();
		result.put("goodsType", goodsTypeList);
		return JSONObject.fromObject(result);
	}

	/**
	 * 获取品牌
	 */
	@Override
	public JSONObject getBrand() {
		
		List<Map<String, Object>> brandList = null;
		Map<String, Object> result = new HashMap<>();
		brandList = ktCountMapper.getBrand();
		result.put("brand", brandList);
		return JSONObject.fromObject(result);
	}

	/**
	 * 获取供应商
	 */
	@Override
	public JSONObject getSupplier() {
		List<Map<String, Object>> supplierList = null;
		Map<String, Object> result = new HashMap<>();
		supplierList = ktCountMapper.getSupplier();
		result.put("supplier", supplierList);
		return JSONObject.fromObject(result);
	}

	/**
	 * 销售流水表
	 */
	@Override
	public JSONObject salesFlowList(Map<String, String> parameter) {
		List<Map<String, Object>> flowList = null;
		flowList = ktCountMapper.salesFlowList(parameter);
		Map<String, Object> result = new HashMap<>();
		result.put("flowList", flowList);
		return JSONObject.fromObject(result);
	}

	/**
	 * 商品类型与品牌级联
	 */
	@Override
	public JSONObject prodTypeLinkBrand(Map<String, String> parameter) {
		List<Map<String, Object>> brandList = null;
		brandList = ktCountMapper.prodTypeLinkBrand(parameter);
		Map<String, Object> result = new HashMap<>();
		result.put("brand", brandList);
		return JSONObject.fromObject(result);
	}

    @Override
    public JSONObject getktTaskAnalyse(Map<String, String> param) {
        Long pageSize = Long.valueOf(param.get("limit"));

        Long page = Long.valueOf(param.get("offset"));

        Long beginNum = page + 1;
        Long endNum = beginNum + pageSize;

        String turnCreateDate = param.get("turnCreateDate");
        String shopId = param.get("shopId");
		if("''".equals(shopId)){
			param.put("shopId",null);
		}else{
			param.put("shopId",shopId);
		}
        String yearInfo = turnCreateDate.substring(0,4);
        param.put("year",yearInfo);

        List<Map<String, Object>> inStoreDOList = null;
        try {
            inStoreDOList = ktCountMapper.selectKtTaskAnalyse(param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String,Object> result = new HashMap<String,Object>();
        result.put("rows",inStoreDOList);
        result.put("total","");
        return JSONObject.fromObject(result);
    }

    @Override
	public JSONObject getKtSsAnalyse(Map<String, String> stringMap) {
		Long pageSize = Long.valueOf(stringMap.get("limit"));

        Long page = Long.valueOf(stringMap.get("offset"));

        Long beginNum = page + 1;
        Long endNum = beginNum + pageSize;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			inStoreDOList = ktCountMapper.selectKtSsAnalyse(stringMap);
			recordCount = ktCountMapper.selectKtSsAnalyseCount(stringMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}
	/**
	 * 库存查询报表
	 */
	@Override
	public JSONObject storeQueryList(Map<String, String> parameter) {
		List<Map<String, Object>> inStoreDOList = null;
		String sumType = parameter.get("sumType");
		String tbRadio = parameter.get("tbRadio");
		//String stock = "1".equals(parameter.get("tbRadio")) ? "o.STOCK" :"o.STOCK/NVL(e.QUANTITY,1)";
		if(sumType.equals("10")){// 按商品库存汇总
			inStoreDOList = ktCountMapper.StoreQueryProductSQL(parameter);
		}else if(sumType.equals("11")){// 按仓库库存汇总
			inStoreDOList = ktCountMapper.StoreQueryShopSQL(parameter);
		}else if(sumType.equals("12")){// 按类别库存汇总
			inStoreDOList = ktCountMapper.StoreQueryTypeSQL(parameter);
		}else if(sumType.equals("13")){// 按品牌库存汇总
			inStoreDOList = ktCountMapper.StoreQueryBrandSQL(parameter);
		}else if(sumType.equals("14")){// 按供应商汇总
			inStoreDOList = ktCountMapper.StoreQuerySupplierSQL(parameter);
		}
		//条包转换
//		if(tbRadio.equals("1")){//1为包
//			if(sumType.equals("10")){// 按商品库存汇总
//				inStoreDOList = ktCountMapper.StoreQueryProductSQLB(parameter);
//			}else if(sumType.equals("11")){// 按仓库库存汇总
//				inStoreDOList = ktCountMapper.StoreQueryShopSQL(parameter);
//			}else if(sumType.equals("12")){// 按类别库存汇总
//				inStoreDOList = ktCountMapper.StoreQueryTypeSQL(parameter);
//			}else if(sumType.equals("13")){// 按品牌库存汇总
//				inStoreDOList = ktCountMapper.StoreQueryBrandSQL(parameter);
//			}else if(sumType.equals("14")){// 按供应商汇总
//				inStoreDOList = ktCountMapper.StoreQuerySupplierSQL(parameter);
//			}
//		}else if(tbRadio.equals("0")){//0为条
//			if(sumType.equals("10")){// 按商品库存汇总
//				inStoreDOList = ktCountMapper.StoreQueryProductSQLT(parameter);
//			}else if(sumType.equals("11")){// 按仓库库存汇总
//				inStoreDOList = ktCountMapper.StoreQueryShopSQL(parameter);
//			}else if(sumType.equals("12")){// 按类别库存汇总
//				inStoreDOList = ktCountMapper.StoreQueryTypeSQL(parameter);
//			}else if(sumType.equals("13")){// 按品牌库存汇总
//				inStoreDOList = ktCountMapper.StoreQueryBrandSQL(parameter);
//			}else if(sumType.equals("14")){// 按供应商汇总
//				inStoreDOList = ktCountMapper.StoreQuerySupplierSQL(parameter);
//			}
//		}
		
		
		Map<String, Object> result = new HashMap<>();
		result.put("rows", inStoreDOList);
		return JSONObject.fromObject(result);
	}

	@Override
	public JSONObject getStockItem(Map<String, String> stringMap,int summaryType) throws CustomException {
		Long pageSize = Long.valueOf(stringMap.get("limit"));

        Long page = Long.valueOf(stringMap.get("offset"));

        Long beginNum = page;
        Long endNum = beginNum + pageSize;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			if(0 == summaryType){
				inStoreDOList = ktCountMapper.selectStockItem(stringMap);
				recordCount = ktCountMapper.selectStockItemCount(stringMap);
			}else{
				inStoreDOList = ktCountMapper.selectStockItemByArea(stringMap);
				recordCount = ktCountMapper.selectStockItemByAreaCount(stringMap);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}

	@Override
	public List<Map<String, String>> findSourceArea() {
		return ktCountMapper.findSourceArea();
	}

	@Override
	public Map<String, Object> getStatisStockItem(String[] ColsName,Map<String, String> params) {
		Map<String, Object> ColsNameMap = Arrays2Map(ColsName);
		Map<String, Object> statisticsRow =  ktCountDao.getStatisStockItem(Arrays.asList(ColsName), params);
		ColsNameMap.putAll(statisticsRow);
		return ColsNameMap;
	}

	@Override
	public JSONObject getSellItem(Map<String, String> stringMap,int summaryType) throws CustomException {
		Long pageSize = Long.valueOf(stringMap.get("limit"));

        Long page = Long.valueOf(stringMap.get("offset"));

        Long beginNum = page;
        Long endNum = beginNum + pageSize;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			if(0 == summaryType){
				inStoreDOList = ktCountMapper.selectSellItem(stringMap);
				recordCount = ktCountMapper.selectSellItemCount(stringMap);
			}else{
				inStoreDOList = ktCountMapper.selectSellItemByArea(stringMap);
				recordCount = ktCountMapper.selectSellItemByAreaCount(stringMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}

	@Override
	public Map<String, Object> getStatisSellItem(String[] ColsName, Map<String, String> params) {
		Map<String, Object> ColsNameMap = Arrays2Map(ColsName);
		Map<String, Object> statisticsRow =  ktCountDao.getStatisSellItem(Arrays.asList(ColsName), params);
		ColsNameMap.putAll(statisticsRow);
		return ColsNameMap;
	}

	@Override
	public JSONObject getCmPerformance(Map<String, String> stringMap) {
		Long pageSize = Long.valueOf(stringMap.get("limit"));

        Long page = Long.valueOf(stringMap.get("offset"));

        Long beginNum = page + 1;
        Long endNum = beginNum + pageSize;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			inStoreDOList = ktCountMapper.selectCmPerformance(stringMap);
			recordCount = ktCountMapper.selectCmPerformanceCount(stringMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}

	@Override
	public Map<String, Object> getStatisCmp(String[] ColsName, Map<String, String> params) {
		Map<String, Object> ColsNameMap = Arrays2Map(ColsName);
		Map<String, Object> statisticsRow =  ktCountDao.getStatisCmp(Arrays.asList(ColsName), params);
		ColsNameMap.putAll(statisticsRow);
		return ColsNameMap;
	}

	@Override
	public JSONObject listIBCPDaily(Map parameter) {
		List<Map<String, Object>> inStoreDOList = null;
		Map<String, Object> result = new HashMap<>();
		try {
			inStoreDOList = ktCountMapper.listIBCPDaily(parameter);
			System.out.println(inStoreDOList);
			Integer a =0,b=0,c=0,d=0;

			for (Map<String,Object> map : inStoreDOList) {
				Object PAYNEWHOUSETODAY = map.get("PAYNEWHOUSETODAY");
				if (PAYNEWHOUSETODAY!=null&&!"".equals(PAYNEWHOUSETODAY)){
					a += Integer.valueOf(PAYNEWHOUSETODAY.toString());
				}
				Object CUMULATIVEPAYMENT = map.get("CUMULATIVEPAYMENT");
				if (CUMULATIVEPAYMENT!=null&&!"".equals(CUMULATIVEPAYMENT)){
					b += Integer.valueOf(CUMULATIVEPAYMENT.toString());
				}
				Object PAYMENTTODAY = map.get("PAYMENTTODAY");
				if (PAYMENTTODAY!=null&&!"".equals(PAYMENTTODAY)){
					c += Integer.valueOf(PAYMENTTODAY.toString());
				}
				Object CUMULATIVEPAYMENTS = map.get("CUMULATIVEPAYMENTS");
				if (CUMULATIVEPAYMENTS!=null&&!"".equals(CUMULATIVEPAYMENTS)){
					d += Integer.valueOf(CUMULATIVEPAYMENTS.toString());
				}
			}
			HashMap<String, Object> countMap = new HashMap<>();
			countMap.put("CUSTMANAGER","合计");
			countMap.put("PAYNEWHOUSETODAY",a);
			countMap.put("CUMULATIVEPAYMENT",b);
			countMap.put("PAYMENTTODAY",c);
			countMap.put("CUMULATIVEPAYMENTS",d);
			inStoreDOList.add(countMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", inStoreDOList.size());
		return JSONObject.fromObject(result);
	}
	@Override
	public JSONObject listTrans(Map <String,String >parameter) {
		Long pageSize = Long.valueOf(parameter.get("limit"));
		Long page = Long.valueOf(parameter.get("offset"));
		Long beginNum = page + 1;
		Long endNum = beginNum + pageSize;

		parameter.put("beginNum",beginNum.toString());
		parameter.put("endNum",endNum.toString());
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			inStoreDOList = ktCountMapper.listTrans(parameter);
			recordCount = ktCountMapper.listTransCount(parameter);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}
	@Override
	public JSONObject listMultBind(Map <String,String >parameter) {
		Long pageSize = Long.valueOf(parameter.get("limit"));
		Long page = Long.valueOf(parameter.get("offset"));
		Long beginNum = page + 1;
		Long endNum = beginNum + pageSize;

		parameter.put("beginNum",beginNum.toString());
		parameter.put("endNum",endNum.toString());
		List<Map<String, Object>> inStoreDOList = null;
		Map<String, Object> result = new HashMap<>();
		try {
			inStoreDOList = ktCountMapper.listMultBind(parameter);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", inStoreDOList.size());
		return JSONObject.fromObject(result);
	}

	@Override
	public JSONObject listMultBindTrans(Map<String, String> params) {
		Long pageSize = Long.valueOf(params.get("limit"));
		Long page = Long.valueOf(params.get("offset"));
		Long beginNum = page + 1;
		Long endNum = beginNum + pageSize;

		params.put("beginNum",beginNum.toString());
		params.put("endNum",endNum.toString());
		List<Map<String, Object>> inStoreDOList = null;
		Map<String, Object> result = new HashMap<>();
		try {
			inStoreDOList = ktCountMapper.listMultBindTrans(params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", inStoreDOList.size());
		return JSONObject.fromObject(result);
	}

	@Override
	public JSONObject getRetailerPayCond(Map<String, String> stringMap) {
		Long pageSize = Long.valueOf(stringMap.get("limit"));

        Long page = Long.valueOf(stringMap.get("offset"));

        Long beginNum = page + 1;
        Long endNum = beginNum + pageSize;

        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			inStoreDOList = ktCountMapper.selectRetailerPayCond(stringMap);
			recordCount = ktCountMapper.selectRetailerPayCondCount(stringMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}

	@Override
	public JSONObject getInstockItem(Map<String, String> stringMap,int summaryType) throws CustomException {
		Long pageSize = Long.valueOf(stringMap.get("limit"));

        Long page = Long.valueOf(stringMap.get("offset"));

        Long beginNum = page;
        Long endNum = beginNum + pageSize;
        stringMap.put("beginNum",beginNum.toString());
        stringMap.put("endNum",endNum.toString());
		List<Map<String, Object>> inStoreDOList = null;
		int recordCount = 0;
		Map<String, Object> result = new HashMap<>();
		try {
			if(summaryType == 0){
				String[] needMergeCols = new String[]{"ID","OPERATOR_TIME"};
				inStoreDOList = mergeCellFunc(ktCountMapper.selectInstockItem(stringMap),needMergeCols);
				recordCount = ktCountMapper.selectInstockItemCount(stringMap);
			}else if(summaryType == 1){
				inStoreDOList = ktCountMapper.selectInstockItemByScode(stringMap);
				recordCount = ktCountMapper.selectInstockItemByScodeCount(stringMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("rows", inStoreDOList);
		result.put("total", recordCount);
		return JSONObject.fromObject(result);
	}

	@Override
	public Map<String, Object> getStatisInstockItem(String[] ColsName, Map<String, String> params) {
		Map<String, Object> ColsNameMap = Arrays2Map(ColsName);
		Map<String, Object> statisticsRow =  ktCountDao.getStatisInstockItem(Arrays.asList(ColsName), params);
		ColsNameMap.putAll(statisticsRow);
		return ColsNameMap;
	}
	
	public List<Map<String, Object>> mergeCellFunc(List<Map<String, Object>> orglst,String[] needMergeCols){
		int[] lastRowIdxs = new int[needMergeCols.length];
		Object[] lastRowVals = new String[needMergeCols.length];
		List<Map<String, Object>> newlst = new ArrayList<Map<String, Object>>();
		for(int i = 0;i < orglst.size(); i++){
			Map<String, Object> map = orglst.get(i);
			for(int j = 0;j < needMergeCols.length;j ++){
				if(lastRowVals[j] != null && (lastRowVals[j]).equals(orglst.get(i).get(needMergeCols[j]))){
					lastRowIdxs[j] = -1;
				}else{
					lastRowIdxs[j] = i;
					lastRowVals[j] = orglst.get(i).get(needMergeCols[j]);
				}
				if(i == (orglst.size() - 1) && (lastRowIdxs[j] == -1)){
					lastRowIdxs[j] = i + 1;
				}
				map.put(needMergeCols[j]+"_IDX", lastRowIdxs[j]);
			}
			newlst.add(map);
		}
		return newlst;
	}

	@Override
	public List<Map<String, Object>> getClerks(Map<String, String> parameter) {
		// TODO Auto-generated method stub
		return ktCountMapper.selectClerks(parameter);
	}


}
